package com.wmh.baseservice.merchant.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.*;
import com.wmh.baseservice.merchant.pojo.MerchantPlotRegion;
import com.wmh.baseservice.merchant.pojo.MerchantVegetable;
import com.wmh.baseservice.merchant.mapper.MerchantVegetableMapper;
import com.wmh.baseservice.merchant.service.MerchantPlotRegionService;
import com.wmh.baseservice.merchant.service.MerchantVegetableService;
import com.wmh.baseservice.common.mybatisplus.methods.CommonServiceImpl;
import com.wmh.baseservice.user.pojo.UsParentOrder;
import com.wmh.baseservice.user.pojo.UsShopCar;
import com.wmh.baseservice.user.pojo.UsVegetableOrder;
import com.wmh.baseservice.user.pojo.vo.VegetableSearch;
import com.wmh.baseservice.user.service.UsParentOrderService;
import com.wmh.baseservice.user.service.UsShopCarService;
import com.wmh.baseservice.user.service.UsVegetableOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author wmh generator
 * @since 2021-12-24
 */
@Service
public class MerchantVegetableServiceImpl extends CommonServiceImpl<MerchantVegetableMapper, MerchantVegetable> implements MerchantVegetableService {

    @Resource
    private MerchantVegetableMapper merchantVegetableMapper;
    @Resource
    private UsShopCarService usShopCarService;
    @Resource
    private MerchantPlotRegionService merchantPlotRegionService;
    @Resource
    private UsVegetableOrderService usVegetableOrderService;
    @Resource
    private UsParentOrderService usParentOrderService;

    @Override
    public IPage<MerchantVegetable> getVegetableList(Page<MerchantVegetable> vegetablePage, Map<String, Object> map) {
        return merchantVegetableMapper.getVegetableList(vegetablePage, map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(MerchantVegetable merchantVegetable) {
        if (!removeById(merchantVegetable.getId())) {
            throw new ServiceException();
        }
        //删除文件夹
        File file = new File(PathUtil.getFullRealPath() + "vegetable/" + merchantVegetable.getUrlId());
        FileUtil.deleteAllFiles(file);
        //删除用户购物车
        if (!usShopCarService.remove(new QueryWrapper<UsShopCar>().eq(UsShopCar.GOODS_ID, merchantVegetable.getId()).eq(UsShopCar.TYPE, 3))) {
            throw new ServiceException();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchSubOrder(List<UsShopCar> usShopCarList, String remark, Integer hasTake) {
        JSONArray orderArray = new JSONArray();
        usShopCarList.forEach(item -> {
            MerchantVegetable merchantVegetable = getByIdForUpdate(item.getGoodsId());
            if (!CommUtil.checkNull(merchantVegetable) || merchantVegetable.getStatus() != 0) {
                usShopCarList.removeIf(iterator -> iterator.getId().equals(item.getId()));
                return;
            }

            //查询所属区域
            MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getByIdForUpdate(merchantVegetable.getRegionId());
            if (!CommUtil.checkNull(merchantPlotRegion)) {
                usShopCarList.removeIf(iterator -> iterator.getId().equals(item.getId()));
                return;
            }

            UsVegetableOrder usVegetableOrder = new UsVegetableOrder();
            //封装参数
            if (item.getSpecialType() == 0) {
                usVegetableOrder.setTotalPrice(merchantVegetable.getPrice().multiply(BigDecimal.valueOf(item.getCount())));
            } else {
                usVegetableOrder.setTotalPrice(merchantVegetable.getGrowPrice().multiply(BigDecimal.valueOf(item.getCount())));
            }
            usVegetableOrder.setRealPrice(usVegetableOrder.getTotalPrice());
            usVegetableOrder.setPlotId(merchantVegetable.getPlotId());
            usVegetableOrder.setOrderNum(UUIDUtil.getTimeId() + UUIDUtil.getLetter());
            usVegetableOrder.setUsId(item.getUsId()).setType(item.getSpecialType() == 0 ? 1 : 2).setRemark(remark);
            usVegetableOrder.setMerchantId(merchantPlotRegion.getMerchantId());
            usVegetableOrder.setMerchantType(merchantPlotRegion.getStatus() == 2 ? 1 : 0);
            usVegetableOrder.setStatus(0);


            //TODO 封装参数
            JSONArray array = new JSONArray();
            JSONObject object = new JSONObject();
           if(item.getSpecialType()==0){
               object.put("amount", item.getCount());
           }
            object.put("standardPrice", item.getSpecialType() == 0 ? merchantVegetable.getPrice() : merchantVegetable.getGrowPrice());
            object.put("overview", merchantVegetable.getOverview());
            object.put("price", usVegetableOrder.getTotalPrice());
            object.put("avatar", merchantVegetable.getAvatar());
            object.put("id", merchantVegetable.getId());
            object.put("title", merchantVegetable.getTitle());
            array.add(object);
            usVegetableOrder.setSnapshot(array.toJSONString());
            if (CommUtil.checkNull(hasTake)) {
                if (usVegetableOrder.getType() == 1) {
                    usVegetableOrder.setHasTake(hasTake == 1 ? 1 : null);
                }
                //自提单生成二维码
                try {
                    JSONObject qrCode = new JSONObject(true);
                    qrCode.put("orderNum", usVegetableOrder.getOrderNum());
                    qrCode.put("type", "vegetable");
                    String paramsQrCode = QrCodeUtil.createParamsQrCode(qrCode.toJSONString(), "/order/", usVegetableOrder.getOrderNum());
                    usVegetableOrder.setQrCode(paramsQrCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            subOrder(merchantVegetable, usVegetableOrder, item);
            orderArray.add(usVegetableOrder.getOrderNum());
        });
        //生成父订单(微信支付传参用)
        UsParentOrder usParentOrder = new UsParentOrder().setSonOrder(orderArray.toJSONString()).setUsId(usShopCarList.get(0).getUsId()).setOrderNum(UUIDUtil.getTimeId().toString())
                .setType(1);
        if (!usParentOrderService.save(usParentOrder)) {
            throw new ServiceException();
        }
        return usParentOrder.getOrderNum();
    }

    @Override
    public IPage<VegetableSearch> search(Page<VegetableSearch> vegetablePage, Map<String, Object> map) {
        return merchantVegetableMapper.search(vegetablePage,map);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void subOrder(MerchantVegetable merchantVegetable, UsVegetableOrder usVegetableOrder, UsShopCar usShopCar) {
        //提交订单
        if (!usVegetableOrderService.save(usVegetableOrder)) {
            throw new ServiceException();
        }
        //修改销量
        merchantVegetable.setSale(merchantVegetable.getSale() + 1);
        if (!updateById(merchantVegetable)) {
            throw new ServiceException();
        }
        //删除购物车
        if (!usShopCarService.removeById(usShopCar)) {
            throw new ServiceException();
        }
    }
}
